package com.yaoweigroup.community.ui.go;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.entity.StringEntity;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.CApplication;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.adapter.LeftAdapter;
import com.yaoweigroup.community.adapter.MainFocusAdapter;
import com.yaoweigroup.community.adapter.RightAadapter;
import com.yaoweigroup.community.adapter.ShopAdapter;
import com.yaoweigroup.community.adapter.ShopGridAdapter;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.enity.Adv;
import com.yaoweigroup.community.enity.ShopType;
import com.yaoweigroup.community.ui.home.MainHomeActivity;
import com.yaoweigroup.community.ui.shop.ShopListActivity;
import com.yaoweigroup.community.util.JsonUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.UtilHttp;

public class GoHomeActivity extends Activity implements OnClickListener,
		OnPageChangeListener {

	private Intent intent;
	// private ListView listView;
	private RelativeLayout v_rl;
	private LinearLayout h_ll;
	private ProgressBar progress;

	private List<ShopType> list;
	private ShopAdapter adapter;
	private ListView left_listView;
	private ListView right_listView;
	private LeftAdapter leftAdapter;
	private RightAadapter rightAdapter;

	private TextView center_tv;

	private ObjectMapper mapper;
	private ImageView back_iv;
	private GridView gridView;
	private ShopGridAdapter gridAdapter;

	private ViewPager viewpager;
	private LinearLayout viewGroup;
	private MainFocusAdapter pagerAdapter;
	private ImageView[] imageViews;
	private List<Adv> advs;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_go_home);
		mapper = new ObjectMapper();
		initRes();
		obtainAdv();
	}

	@Override
	protected void onResume() {
		super.onResume();
		center_tv.setText("社区超市");
		v_rl.setVisibility(View.VISIBLE);
		h_ll.setVisibility(View.GONE);
	}

	private void initRes() {

		viewpager = (ViewPager) findViewById(R.id.viewpager);
		viewGroup = (LinearLayout) findViewById(R.id.viewGroup);

		advs = new ArrayList<Adv>();
		pagerAdapter = new MainFocusAdapter(advs, this);
		viewpager.setAdapter(pagerAdapter);
		viewpager.setOnPageChangeListener(this);
		viewpager.setCurrentItem(0);

		center_tv = (TextView) findViewById(R.id.center_tv);
		back_iv = (ImageView) findViewById(R.id.back_iv);
		back_iv.setOnClickListener(this);
		left_listView = (ListView) findViewById(R.id.left_listView);
		right_listView = (ListView) findViewById(R.id.right_listView);
		gridView = (GridView) findViewById(R.id.gridView);
		v_rl = (RelativeLayout) findViewById(R.id.v_rl);
		h_ll = (LinearLayout) findViewById(R.id.h_ll);
		progress = (ProgressBar) findViewById(R.id.progress);

		list = new ArrayList<ShopType>();
		adapter = new ShopAdapter(this, list);
		gridAdapter = new ShopGridAdapter(this, list);
		gridView.setAdapter(gridAdapter);
		leftAdapter = new LeftAdapter(this, list);
		leftAdapter.setSelectPosition(0);
		left_listView.setAdapter(leftAdapter);

		rightAdapter = new RightAadapter(this, list);
		right_listView.setAdapter(rightAdapter);

		gridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				center_tv.setText(oneTypes.get(arg2).getTypename());
				twoTypes.clear();
				if (oneTypes != null && oneTypes.size() > 0) {
					for (ShopType type : types) {
						if (oneTypes.get(arg2).getId() == type.getSubid()) {
							twoTypes.add(type);
						}
					}
				}
				if (twoTypes.size() == 0) {
					Toast.makeText(GoHomeActivity.this, "暂无类型数据!", 500).show();
				}
				h_ll.setVisibility(View.VISIBLE);
				v_rl.setVisibility(View.GONE);
				LogUtil.d("wxf", "twoTypes=" + twoTypes.size());
				threeTypes.clear();
				leftAdapter.setDataChange(twoTypes);
				if (twoTypes.size() > 0) {
					threeTypes.add(twoTypes.get(0));
					for (ShopType type : types) {
						if (twoTypes.get(0).getId() == type.getSubid()) {
							threeTypes.add(type);
						}
					}
					rightAdapter.setDataChange(threeTypes);
				}

			}
		});

		left_listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {

				threeTypes.clear();
				threeTypes.add(twoTypes.get(position));
				for (ShopType type : types) {
					if (twoTypes.get(position).getId() == type.getSubid()) {
						threeTypes.add(type);
					}
				}
				leftAdapter.setSelectPosition(position);
				rightAdapter.setDataChange(threeTypes);
			}
		});
		obtainData();

		right_listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				ShopType type = threeTypes.get(arg2);
				Intent intent = new Intent(GoHomeActivity.this,
						ShopListActivity.class);
				intent.putExtra("type", type);
				startActivity(intent);
			}
		});
	}

	private void setImageBackground(int selectItems) {
		for (int i = 0; i < imageViews.length; i++) {
			if (i == selectItems) {
				imageViews[i].setBackgroundResource(R.drawable.new_focus_icon);
			} else {
				imageViews[i]
						.setBackgroundResource(R.drawable.new_unfocus_icon);
			}
		}
	}

	private List<ShopType> types = null;

	private void obtainAdv() {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("typename", "APPShop");
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.advertisement, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							advs = mapper.readValue(data,
									new TypeReference<List<Adv>>() {
									});
							if (state == 200) {
								handler.sendEmptyMessage(DATA_SUCCESS);
							} else {
								handler.sendEmptyMessage(DATA_FAIL);
							}

						} catch (Exception e) {
							handler.sendEmptyMessage(DATA_FAIL);
							LogUtil.e("wxf", e.toString());
						}

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(DATA_FAIL);

					}

				});
	}

	private void obtainData() {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		JsonUtil jsonUtil = new JsonUtil();
		jsonUtil.add("typeid", 0);
		LogUtil.d("wxf", jsonUtil.toString());
		StringEntity enity = null;
		try {
			enity = new StringEntity(jsonUtil.toString());
		} catch (Exception e) {
			LogUtil.e("wxf", e.toString());
		}
		params.setContentType("application/json");
		params.setBodyEntity(enity);
		params.setHeader("Accept", "application/json");
		http.send(HttpRequest.HttpMethod.POST, Urls.getProductType, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						LogUtil.d("wxf", "result = " + responseInfo.result);
						String result = responseInfo.result;
						try {
							JSONObject obj = new JSONObject(result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							CApplication.cache.put(Urls.getProductType, data);
							if (state == 200) {
								types = mapper.readValue(data,
										new TypeReference<List<ShopType>>() {
										});
								handler.sendEmptyMessage(TYPE_SUCCESS);

							} else {
								handler.sendEmptyMessage(TYPE_FAIL);

							}
						} catch (Exception e) {
							handler.sendEmptyMessage(TYPE_FAIL);
							LogUtil.e("wxf", e.toString());
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						LogUtil.e("wxf", error.toString());
						handler.sendEmptyMessage(TYPE_FAIL);
					}

				});
	}

	public final int TYPE_SUCCESS = 0x2210;
	public final int TYPE_FAIL = TYPE_SUCCESS + 1;
	public final int DATA_SUCCESS = TYPE_SUCCESS + 2;
	public final int DATA_FAIL = TYPE_SUCCESS + 3;
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case TYPE_SUCCESS:
				doData();
				progress.setVisibility(View.GONE);
				break;
			case TYPE_FAIL:
				progress.setVisibility(View.GONE);
				break;
			case DATA_SUCCESS:
				progress.setVisibility(View.GONE);
				if (advs != null && advs.size() > 0) {
					imageViews = new ImageView[advs.size()];
					for (int i = 0; i < advs.size(); i++) {
						LinearLayout.LayoutParams parmas = new LinearLayout.LayoutParams(
								12, 12);
						parmas.leftMargin = 5;
						parmas.rightMargin = 5;
						ImageView imageView = new ImageView(GoHomeActivity.this);
						imageView.setLayoutParams(parmas);
						imageViews[i] = imageView;
						if (i == 0) {
							imageView
									.setBackgroundResource(R.drawable.new_focus_icon);
						} else {
							imageView
									.setBackgroundResource(R.drawable.new_unfocus_icon);
						}
						viewGroup.addView(imageView);
					}
					pagerAdapter.setDataChange(advs);
				}
				break;
			case DATA_FAIL:
				progress.setVisibility(View.GONE);
				break;
			}
		};
	};

	private List<ShopType> oneTypes;
	private List<ShopType> twoTypes;
	private List<ShopType> threeTypes;

	private void doData() {
		oneTypes = new ArrayList<ShopType>();
		twoTypes = new ArrayList<ShopType>();
		threeTypes = new ArrayList<ShopType>();
		if (types == null) {
			progress.setVisibility(View.GONE);
			return;
		}
		for (ShopType oneType : types) {
			if (oneType.getSubid() == 0) {
				oneTypes.add(oneType);
			}
		}
		gridAdapter.setDataChange(oneTypes);
		adapter.setDataChange(oneTypes);
		if (oneTypes.size() > 0) {
			for (ShopType oneType : types) {
				if (oneType.getSubid() == oneTypes.get(0).getId()) {
					twoTypes.add(oneType);
				}
			}
		}

	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.back_iv:
			center_tv.setText("社区超市");
			v_rl.setVisibility(View.VISIBLE);
			h_ll.setVisibility(View.GONE);
			break;
		}
	}

	private long firstTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			long secondTime = System.currentTimeMillis();
			if (secondTime - firstTime > 2000) { // 如果两次按键时间间隔大于2秒，则不退出
				Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
				firstTime = secondTime;// 更新firstTime
				return true;
			} else { // 两次按键小于2秒时，退出应用
				System.exit(0);
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onPageSelected(int arg0) {
		setImageBackground(arg0);
	}
}
